export default {
	queryByPage(config, msgObj,callbackObject) {	
		RongIMLib.RongIMClient.connect(config.token, {
			onSuccess: function(userId) {
				console.log(userId+"登录成功！！！");
                RongIMLib.RongIMClient.getInstance().getHistoryMessages(msgObj.type, msgObj.targetId, 0, 20, callbackObject);			
			},
			onTokenIncorrect: function() {
				console.log('token无效');
			},
			onError: function(errorCode) {
				var info = '';
				switch(errorCode) {
					case RongIMLib.ErrorCode.TIMEOUT:
						info = '超时';
						break;
					case RongIMLib.ErrorCode.UNKNOWN_ERROR:22
						info = '未知错误';
						break;
					case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
						info = '不可接受的协议queryAll版本';
						break;
					case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
						info = 'appkey不正确';
						break;
					case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
						info = '服务器不可用';
						break;
				}
				console.log(errorCode);
			}
		});
	},	
	save(config,msgObj,callbackObject){
		console.log("进入发送save...");
		RongIMLib.RongIMClient.getInstance().sendMessage(msgObj.type, msgObj.targetId, msgObj.msg,callbackObject);	
	},
	convertMsg(SDKmsg) {
		var msg = new RongIMLib.Message();
		msg.conversationType = SDKmsg.conversationType;
		msg.extra = SDKmsg.extra;
		msg.objectName = SDKmsg.objectName;
		msg.messageDirection = SDKmsg.messageDirection;
		msg.messageId = SDKmsg.messageId;
		msg.receivedStatus = SDKmsg.receivedStatus;
		msg.receivedTime = new Date(SDKmsg.receivedTime);
		msg.senderUserId = SDKmsg.senderUserId;
		msg.sentStatus = SDKmsg.sendStatusMessage;
		msg.sentTime = new Date(SDKmsg.sentTime);
		msg.targetId = SDKmsg.targetId;
		msg.messageType = SDKmsg.messageType;
		switch(msg.messageType) {
			case RongIMLib.RongIMClient.MessageType.TextMessage:
			//debugger;
				var texmsg = new TextMessage();
				var content = SDKmsg.content.content;
				content = RongWebIMWidget.Helper.escapeSymbol.encodeHtmlsymbol(content);
				content = RongWebIMWidget.Helper.discernUrlEmailInStr(content);
				if(RongIMLib.RongIMEmoji && RongIMLib.RongIMEmoji.emojiToHTML) {
					content = RongIMLib.RongIMEmoji.emojiToHTML(content);
				}
				texmsg.content = content;
				texmsg.extra = SDKmsg.content.extra;
				msg.content = texmsg;
				break;
			case RongIMLib.RongIMClient.MessageType.ImageMessage:
				var image = new ImageMessage();
				var content = SDKmsg.content.content || "";
				if(content.indexOf("base64,") == -1) {
					content = "data:image/png;base64," + content;
				}
				image.content = content;
				image.imageUri = SDKmsg.content.imageUri;
				image.extra = SDKmsg.content.extra;
				msg.content = image;
				break;
			case RongIMLib.RongIMClient.MessageType.VoiceMessage:
				var voice = new VoiceMessage();
				voice.content = SDKmsg.content.content;
				voice.duration = SDKmsg.content.duration;
				voice.extra = SDKmsg.content.extra;
				msg.content = voice;
				break;
			case RongIMLib.RongIMClient.MessageType.RichContentMessage:
				var rich = new RichContentMessage();
				rich.content = SDKmsg.content.content;
				rich.title = SDKmsg.content.title;
				rich.imageUri = SDKmsg.content.imageUri;
				rich.extra = SDKmsg.content.extra;
				msg.content = rich;
				break;
			case RongIMLib.RongIMClient.MessageType.LocationMessage:
				var location = new LocationMessage();
				var content = SDKmsg.content.content || "";
				if(content.indexOf("base64,") == -1) {
					content = "data:image/png;base64," + content;
				}
				location.content = content;
				location.latiude = SDKmsg.content.latiude;
				location.longitude = SDKmsg.content.longitude;
				location.poi = SDKmsg.content.poi;
				location.extra = SDKmsg.content.extra;
				msg.content = location;
				break;
			case RongIMLib.RongIMClient.MessageType.InformationNotificationMessage:
				var info = new InformationNotificationMessage();
				msg.panelType = 2; //灰条消息
				info.content = SDKmsg.content.message;
				msg.content = info;
				break;
			case RongIMLib.RongIMClient.MessageType.DiscussionNotificationMessage:
				var discussion = new DiscussionNotificationMessage();
				discussion.extension = SDKmsg.content.extension;
				discussion.operation = SDKmsg.content.operation;
				discussion.type = SDKmsg.content.type;
				discussion.isHasReceived = SDKmsg.content.isHasReceived;
				msg.content = discussion;
			case RongIMLib.RongIMClient.MessageType.HandShakeResponseMessage:
				var handshak = new HandShakeResponseMessage();
				handshak.status = SDKmsg.content.status;
				handshak.msg = SDKmsg.content.msg;
				handshak.data = SDKmsg.content.data;
				msg.content = handshak;
				break;
			case RongIMLib.RongIMClient.MessageType.ChangeModeResponseMessage:
				var change = new ChangeModeResponseMessage();
				change.code = SDKmsg.content.code;
				change.data = SDKmsg.content.data;
				change.status = SDKmsg.content.status;
				msg.content = change;
				break;
			case RongIMLib.RongIMClient.MessageType.CustomerStatusUpdateMessage:
				var up = new CustomerStatusUpdateMessage();
				up.serviceStatus = SDKmsg.content.serviceStatus;
				msg.content = up;
				break;
			case RongIMLib.RongIMClient.MessageType.TerminateMessage:
				var ter = new TerminateMessage();
				ter.code = SDKmsg.content.code;
				msg.content = ter;
				break;
			default:
				break;
		}
		if(msg.content) {
			msg.content.userInfo = SDKmsg.content.user;
		}
		return msg;
	},

}
	var TextMessage = (function() {
		function TextMessage(msg) {

		}
		return TextMessage;
	})();
    
    var ImageMessage = (function () {
        function ImageMessage() {
        }
        return ImageMessage;
    })();
    
var RongWebIMWidget;
(function (RongWebIMWidget) {
    var userAgent = window.navigator.userAgent.toLowerCase();
    var Helper = (function () {
        function Helper() {
        }
        Helper.timeCompare = function (first, second) {
            var pre = first.toString();
            var cur = second.toString();
            return pre.substring(0, pre.lastIndexOf(":")) == cur.substring(0, cur.lastIndexOf(":"));
        };
        Helper.cloneObject = function (obj) {
            if (!obj)
                return null;
            var ret;
            if (Object.prototype.toString.call(obj) == "[object Array]") {
                ret = [];
                var i = obj.length;
                while (i--) {
                    ret[i] = Helper.cloneObject(obj[i]);
                }
                return ret;
            }
            else if (typeof obj === "object") {
                ret = {};
                for (var item in obj) {
                    ret[item] = obj[item];
                }
                return ret;
            }
            else {
                return obj;
            }
        };
        Helper.discernUrlEmailInStr = function (str) {
            var html;
            var EMailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/gi;
            var EMailArr = [];
            html = str.replace(EMailReg, function (str) {
                EMailArr.push(str);
                return '[email`' + (EMailArr.length - 1) + ']';
            });
            var URLReg = /(((ht|f)tp(s?))\:\/\/)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|cn|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk|me|im))(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&amp;%\$#\=~_\-]+))*/gi;
            html = html.replace(URLReg, function (str, $1) {
                if ($1) {
                    return '<a target="_blank" href="' + str + '">' + str + '</a>';
                }
                else {
                    return '<a target="_blank" href="//' + str + '">' + str + '</a>';
                }
            });
            for (var i = 0, len = EMailArr.length; i < len; i++) {
                html = html.replace('[email`' + i + ']', '<a href="mailto:' + EMailArr[i] + '">' + EMailArr[i] + '<a>');
            }
            return html;
        };
        Helper.checkType = function (obj) {
            var type = Object.prototype.toString.call(obj);
            return type.substring(8, type.length - 1).toLowerCase();
        };
        Helper.browser = {
            version: (userAgent.match(/.+(?:rv|it|ra|chrome|ie)[\/: ]([\d.]+)/) || [0, '0'])[1],
            safari: /webkit/.test(userAgent),
            opera: /opera|opr/.test(userAgent),
            msie: /msie|trident/.test(userAgent) && !/opera/.test(userAgent),
            chrome: /chrome/.test(userAgent),
            mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit|like gecko)/.test(userAgent)
        };
        Helper.escapeSymbol = {
            encodeHtmlsymbol: function (str) {
                if (!str)
                    return '';
                str = str.replace(/&/g, '&amp;');
                str = str.replace(/</g, '&lt;');
                str = str.replace(/>/g, '&gt;');
                str = str.replace(/"/g, '&quot;');
                str = str.replace(/'/g, '&#039;');
                return str;
            },
            decodeHtmlsymbol: function (str) {
                if (!str)
                    return '';
                str = str.replace(/&amp;/g, '&');
                str = str.replace(/&lt;/g, '<');
                str = str.replace(/&gt;/g, '>');
                str = str.replace(/&quot;/g, '"');
                str = str.replace(/&#039;/g, '\'');
                return str;
            }
        };
        Helper.getFocus = function (obj) {
            obj.focus();
            if (obj.createTextRange) {
                var rtextRange = obj.createTextRange();
                rtextRange.moveStart('character', obj.value.length);
                rtextRange.collapse(true);
                rtextRange.select();
            }
            else if (obj.selectionStart) {
                obj.selectionStart = obj.value.length;
            }
            else if (window.getSelection && obj.lastChild) {
                var sel = window.getSelection();
                var tempRange = document.createRange();
                if (Helper.browser.msie) {
                    tempRange.setStart(obj.lastChild, obj.lastChild.length);
                }
                else {
                    tempRange.setStart(obj.firstChild, obj.firstChild.length);
                }
                sel.removeAllRanges();
                sel.addRange(tempRange);
            }
        };
        Helper.ImageHelper = {
            getThumbnail: function (obj, area, callback) {
                var canvas = document.createElement("canvas"), context = canvas.getContext('2d');
                var img = new Image();
                img.onload = function () {
                    var target_w;
                    var target_h;
                    var imgarea = img.width * img.height;
                    if (imgarea > area) {
                        var scale = Math.sqrt(imgarea / area);
                        scale = Math.ceil(scale * 100) / 100;
                        target_w = img.width / scale;
                        target_h = img.height / scale;
                    }
                    else {
                        target_w = img.width;
                        target_h = img.height;
                    }
                    canvas.width = target_w;
                    canvas.height = target_h;
                    context.drawImage(img, 0, 0, target_w, target_h);
                    try {
                        var _canvas = canvas.toDataURL("image/jpeg", 0.5);
                        _canvas = _canvas.substr(23);
                        callback(obj, _canvas);
                    }
                    catch (e) {
                        callback(obj, null);
                    }
                };
                if (typeof obj == 'string') {
                    img.src = obj;
                }
                else {
                    img.src = Helper.ImageHelper.getFullPath(obj);
                }
            },
            getFullPath: function (file) {
                window.URL = window.URL || window.webkitURL;
                if (window.URL && window.URL.createObjectURL) {
                    return window.URL.createObjectURL(file);
                }
                else {
                    return null;
                }
            }
        };
        Helper.CookieHelper = {
            setCookie: function (name, value, exires) {
                if (exires) {
                    var date = new Date();
                    date.setDate(date.getDate() + exires);
                    document.cookie = name + "=" + encodeURI(value) + ";expires=" + date.toUTCString();
                }
                else {
                    document.cookie = name + "=" + encodeURI(value) + ";";
                }
            },
            getCookie: function (name) {
                var start = document.cookie.indexOf(name + "=");
                if (start != -1) {
                    var end = document.cookie.indexOf(";", start);
                    if (end == -1) {
                        end = document.cookie.length;
                    }
                    return decodeURI(document.cookie.substring(start + name.length + 1, end));
                }
                else {
                    return "";
                }
            },
            removeCookie: function (name) {
                var con = this.getCookie(name);
                if (con) {
                    this.setCookie(name, "con", -1);
                }
            }
        };
        return Helper;
    })();
    RongWebIMWidget.Helper = Helper;
    var NotificationHelper = (function () {
        function NotificationHelper() {
        }
        NotificationHelper.isNotificationSupported = function () {
            return (typeof Notification === "function" || typeof Notification === "object");
        };
        NotificationHelper.requestPermission = function () {
            if (!NotificationHelper.isNotificationSupported()) {
                return;
            }
            Notification.requestPermission(function (status) {
            });
        };
        NotificationHelper.onclick = function (n) { };
        NotificationHelper.showNotification = function (config) {
            if (!NotificationHelper.isNotificationSupported()) {
                console.log('the current browser does not support Notification API');
                return;
            }
            if (Notification.permission !== "granted") {
                console.log('the current page has not been granted for notification');
                return;
            }
            if (!NotificationHelper.desktopNotification) {
                return;
            }
            var title = config.title;
            delete config.title;
            var n = new Notification(title, config);
            n.onshow = function () {
                setTimeout(function () {
                    n.close();
                }, 5000);
            };
            n.onclick = function () {
                window.focus();
                NotificationHelper.onclick && NotificationHelper.onclick(n);
                n.close();
            };
            n.onerror = function () {
            };
            n.onclose = function () {
            };
        };
        NotificationHelper.desktopNotification = true;
        return NotificationHelper;
    })();
    RongWebIMWidget.NotificationHelper = NotificationHelper;
    var DirectiveFactory = (function () {
        function DirectiveFactory() {
        }
        DirectiveFactory.GetFactoryFor = function (classType) {
            var factory = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i - 0] = arguments[_i];
                }
                var newInstance = Object.create(classType.prototype);
                newInstance.constructor.apply(newInstance, args);
                return newInstance;
            };
            factory.$inject = classType.$inject;
            return factory;
        };
        return DirectiveFactory;
    })();
    RongWebIMWidget.DirectiveFactory = DirectiveFactory;
    var errSrc = (function () {
        function errSrc() {
        }
        errSrc.instance = function () {
            return new errSrc();
        };
        errSrc.prototype.link = function (scope, element, attrs) {
            if (!attrs["ngSrc"]) {
                attrs.$set('src', attrs["errSrc"]);
            }
            element.bind('error', function () {
                if (attrs["src"] != attrs["errSrc"]) {
                    attrs.$set('src', attrs["errSrc"]);
                }
            });
        };
        return errSrc;
    })();
    var contenteditableDire = (function () {
        function contenteditableDire() {
            this.restrict = 'A';
            this.require = '?ngModel';
        }
        contenteditableDire.prototype.link = function (scope, element, attrs, ngModel) {
            function replacemy(e) {
                return e.replace(new RegExp("<[\\s\\S.]*?>", "ig"), "");
            }
            var domElement = element[0];
            scope.$watch(function () {
                return ngModel.$modelValue;
            }, function (newVal) {
                if (document.activeElement === domElement) {
                    return;
                }
                if (newVal === '' || newVal === attrs["placeholder"]) {
                    domElement.innerHTML = attrs["placeholder"];
                    domElement.style.color = "#a9a9a9";
                    ngModel.$setViewValue("");
                }
            });
            element.bind('focus', function () {
                if (domElement.innerHTML == attrs["placeholder"]) {
                    domElement.innerHTML = '';
                }
                domElement.style.color = '';
            });
            element.bind('blur', function () {
                if (domElement.innerHTML === '') {
                    domElement.innerHTML = attrs["placeholder"];
                    domElement.style.color = "#a9a9a9";
                }
            });
            if (!ngModel)
                return;
            element.bind("paste", function (e) {
                var that = this;
                var content;
                e.preventDefault();
                if (e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData)) {
                    // originalEvent jQuery中的
                    content = (e.originalEvent || e).clipboardData.getData('text/plain');
                    content = replacemy(content || '');
                    content && document.execCommand('insertText', false, content);
                }
                else if (window['clipboardData']) {
                    content = window['clipboardData'].getData('Text');
                    content = replacemy(content || '');
                    if (document['selection']) {
                        content && document['selection'].createRange().pasteHTML(content);
                    }
                    else if (document.getSelection) {
                        document.getSelection().getRangeAt(0).insertNode(document.createTextNode(content));
                    }
                }
                ngModel.$setViewValue(that.innerHTML);
            });
            ngModel.$render = function () {
                element.html(ngModel.$viewValue || '');
            };
            element.bind("keyup paste", read);
            element.bind("input", read);
            function read() {
                var html = element.html();
                var html = Helper.escapeSymbol.decodeHtmlsymbol(html);
                html = html.replace(/^<br>$/i, "");
                html = html.replace(/<br>/gi, "\n");
                if (attrs["stripBr"] && html == '<br>') {
                    html = '';
                }
                ngModel.$setViewValue(html);
            }
        };
        return contenteditableDire;
    })();
    var ctrlEnterKeys = (function () {
        function ctrlEnterKeys() {
            this.restrict = "A";
            this.require = '?ngModel';
            this.scope = {
                fun: "&",
                ctrlenter: "=",
                content: "="
            };
        }
        ctrlEnterKeys.prototype.link = function (scope, element, attrs, ngModel) {
            scope.ctrlenter = scope.ctrlenter || false;
            element.bind("keypress", function (e) {
                if (scope.ctrlenter) {
                    if (e.ctrlKey === true && e.keyCode === 13 || e.keyCode === 10) {
                        scope.fun();
                        scope.$parent.$apply();
                        e.preventDefault();
                    }
                }
                else {
                    if (e.ctrlKey === false && e.shiftKey === false && (e.keyCode === 13 || e.keyCode === 10)) {
                        scope.fun();
                        scope.$parent.$apply();
                        e.preventDefault();
                    }
                    else if (e.ctrlKey === true && e.keyCode === 13 || e.keyCode === 10) {
                    }
                }
            });
        };
        return ctrlEnterKeys;
    })();
//  angular.module("RongWebIMWidget")
//      .directive('errSrc', errSrc.instance)
//      .directive("contenteditableDire", DirectiveFactory.GetFactoryFor(contenteditableDire))
//      .directive("ctrlEnterKeys", DirectiveFactory.GetFactoryFor(ctrlEnterKeys))
//      .filter('trustHtml', ["$sce", function ($sce) {
//          return function (str) {
//              var trustAsHtml = $sce.trustAsHtml(str);
//              return trustAsHtml;
//          };
//      }]).filter("historyTime", ["$filter", function ($filter) {
//          return function (time) {
//              var today = new Date();
//              if (time.toDateString() === today.toDateString()) {
//                  return $filter("date")(time, "HH:mm");
//              }
//              else if (time.toDateString() === new Date(today.setTime(today.getTime() - 1)).toDateString()) {
//                  return "昨天" + $filter("date")(time, "HH:mm");
//              }
//              else {
//                  return $filter("date")(time, "yyyy-MM-dd HH:mm");
//              }
//          };
//      }]);
})(RongWebIMWidget || (RongWebIMWidget = {}));